// 记录用户最后一次操作的时间
var lastOpTime
// 时间戳的间隔时间
var INTERVAL = 60 * 1000

// 是否已经登录
var isLogined = false



// 信息传输对象
var Message = {
    fromId: 	null,
    fromName: 	null,
    toId:	null,
    toName:	null,
    msg:	"",
    isFirst: 	true,
    timestamp: 	'',
    mime:	'text',	/* text,img */
    isRead:	true,	/* 信息默认已读 */
}

/**
 * 从iframe中获取待发送的记录
 */
var messages = function() {
    var messageArr = []
    var nodes = $(window.editor.cmd.doc.body)[0].childNodes
    var node, msg
    for(var i=0,len=nodes.length;i<len;i++){
	node = nodes[i]
	var temp = Object.assign({}, Message)
	if(i==1) {
	    temp.isFirst = false 
	}
	if((msg=node.src) != undefined) {
	    temp.mime = 'img'
	} else if((msg=node.data) != undefined) {
	    temp.mime = 'text'
	} else {
	    msg = ''
	}
	temp.msg = msg.trim()
	if(msg==undefined){
	    console.log('waring: message parse error')
	    continue
	}
	messageArr.push(temp)
    }
    return messageArr
}











var resendBind = function() {
    $('.send-fail').click(function() {
      var pRight = $(this).parent('.right')
      var cChatContent = $(pRight).find('.text .chat-content')
      var str = $(cChatContent).text().trim()
      Message.msg = str
      // addChatRecord(Message)
      genSendTag(Message)
    })
  }


// 封装的WebSocket对象
var WS = {
    webSocket: null,
    retryCount:		0,	/* 重连的次数 */
    tryIndex:		10,	/* 当前重连的次数 */
    send: function(msgObj) {
	try {
	    msgObj.timestamp = new Date().getTime()
	    if('img' == msgObj.mime) {
		// 如果是图片，则采用ajax的形式
		    $.post("http://"+ PLATFORM.getPath()+"/chat/clientSendImg.json", {
			"msg": JSON.stringify(msgObj)
	   	      },function(data) {
	   		 if(data.isSucc == 1) {
	   		     
	   		 } else {
	   		     
	   		 }
	   	      }, "json")
	    } else {
		this.webSocket.send(JSON.stringify(msgObj))
	    }
	    Message.isFirst = false
	} catch(e) {
	    console.log('the websocket is not ready')
	}
    },
    
    link: function(url) {
	if('WebSocket' in window) {
	    try {
		this.webSocket = new WebSocket(url)
	    } catch(e) {
		
	    }
	    
	    // 绑定最基本的俩个事件
	    this.webSocket.onerror = function () {
		if(WS.tryIndex > WS.retryCount) {
		    $('.link-msg').text('服务器故障...')
		    console.log('link failed')
		    WS.webSocket = null
		    return false
		}
		console.log('[' + WS.tryIndex + "/" + WS.retryCount+']'+'link failed,try again...')
		$('.link-msg').text('连接服务器失败，尝试第'+((WS.tryIndex)++)+'次连接...')
		WS.link(url)
	    }
	    this.webSocket.onclose = function () {
		if(WS.tryIndex > WS.retryCount) {
		    $('.link-msg').text('服务器故障...')
		    console.log('link failed')
		    WS.webSocket = null
		    return false
		}
		console.log('[' + WS.tryIndex + "/" + WS.retryCount+']'+'link failed,try again...')
		$('.link-msg').text('连接服务器失败，尝试第'+((WS.tryIndex)++)+'次连接...')
		WS.link(url)
		// $('.link-msg').css('display', 'block')
	    }
	    this.webSocket.onopen = function() {
		window.editor.focus()
		$('.link-msg').css('display', 'none')
	    }
	    this.webSocket.onmessage = function(event) {
		var msgObj = JSON.parse(event.data)
		if('img' == msgObj.mime) {
		      $.ajax({
			     	type: "post",
			        url: "http://"+ PLATFORM.getPath()+"/chat/getImg.json",
			        async: false,
			        dataType: "json",
			        data: {
			            'url': msgObj.msg
			        },
			        success: function(data) {
			            if(data.isSucc == '1') {
			        	msgObj.msg = data.result
			            } else {
			        	
			            }
			        }
			      });		    
		} 
		if(msgObj.isRead && msgObj.isFirst) {
		    Message.toId = msgObj.fromId
		    Message.toName = msgObj.fromName || '工号'+msgObj.fromId
		    // 生成tab
		    genLinkingHTML(Message)
		    // 修改标题
		    $('.right-title span').text(msgObj.fromName)
		    // 修改正在联系人的个数
		    var lc = $('.links-count')
		    lc.text(parseInt(lc.text()) + 1)
		    genRecvTag(msgObj)
		} else {
		    $('.addition').css('display', 'none')
		    Message.msg = msgObj.msg
		    // addChatRecord(Message)
		    setLinker(Message.toId, $('.chat-msg').html())
		    if(canDirectGen(msgObj)) {
			// 如果可以直接生成
			genRecvTag(msgObj)
		    } else {
			// 生成消息提醒气泡
			msgTip(msgObj)
			// 将信息预存到localstorage中
			prestore(msgObj)
		    }
		}
	    }
	} else {
	    alert('该浏览器不支持WebSocket！请使用较高版本的谷歌或火狐浏览器！')
	}
    },
    
    bindRecv: function(fun) {
	this.webSocket.onmessage = fun
    },
    
}


var viewerUpdate = function() {
    setTimeout(function(){$('.chat-msg').viewer('update')},150)
} 


function prestore(msgObj) {
    var str = msgObj.msg
    if(msgIsImg(msgObj)){
	str = genImgFromBase64Str(str)
    }
    // "<img src='img/user.png' alt='头像1'>"+
    var recodes = getLinker(msgObj.fromId)
    var htmlStr = "<div class='left'>" +
    "<div class='head-img'>" +
    	"<div style=\""+"background-image:url('img/user.png')"+"\"></div>"+
    "</div>"+
    "<div class='text'>"+
    "<span class='chat-content'>"+ str+ "</span></div></div></div>"
	recodes += htmlStr
	try {
	    setLinker(msgObj.fromId, recodes)
	} catch(e) {
	    if (e.name == 'QuotaExceededError') {
		// 存放满了，清除缓存
		localStorage.clear()
	    }
	}
}

function msgTip(msgObj) {
    var toIdStr = $('.user-tab-choosed .username').attr('data-msg')
    var shouldShowId = JSON.parse(toIdStr).toId
    if(msgObj.fromId == shouldShowId) {
	return true
    }
    var users = $('.username')
    var u
    var count
    var countStr
    for(var i=0,len=users.length; i<len; i++) {
	u = users[i]
	if($(u).text() == msgObj.fromName) {
	    countStr = $(u).next('b').text()
	    $(u).next('b').css('display', 'initial')
	    if(countStr == '') {
		$(u).next('b').text(1)
	    } else if(countStr == '99'){
		$(u).next('b').text('99+')
	    } else if(countStr == '99+'){
		return
	    } else {
		count = parseInt(countStr)
		$(u).next('b').text(count+1)
	    }
	    return
	}
    }
}


function canDirectGen(msgObj) {
    
    if(msgObj.isRead) {
	var toIdStr = $('.user-tab-choosed .username').attr('data-msg')
	    // 如果没有跟任何人聊天，可以直接生成
	    if(toIdStr == undefined) {
		return true
	    } 
	    
	    var shouldShowId = JSON.parse(toIdStr).toId
	    if(msgObj.fromId == shouldShowId) {
		return true
	    }
	    return false
    } else {
	var toIdStr = $('.user-tab-choosed .username').attr('data-msg')
	if(toIdStr == undefined) {
	    genLinkingHTML(msgObj)
	    $('.right-title span').text(msgObj.fromName)
	} 
	return true
    }
}


/*
 * 判断信息是否为图片，如果为图片，则返回true，否则返回false
 */
function msgIsImg(msgObj) {
    if(msgObj.mime == 'img') {
	return true
    }
    return false
}

/**
 * 从base64编码中生成图片标签
 */
function genImgFromBase64Str(base64Str) {
    var img = $("<img src='"+base64Str+"'>")
    var width = img.width
    var widthAfterCalc
    if(width > 1000) {
      widthAfterCalc = width * 0.4 +"px"
    } else if(width > 500) {
      widthAfterCalc = width * 0.7 +"px"
    } else if(width > 200) {
      widthAfterCalc = width * 0.9 +"px"
    } else {
      widthAfterCalc = width +"px"
    }
    return "<img src='"+base64Str+"' style='width:"+widthAfterCalc+";'>"
}

function evaluateCancel() {
    Horn.getComp('evaluateWin').hide()
}

function evaluateOK() {
    var liTab = $('.user-tab.user-tab-choosed .username')
    var msgObj = JSON.parse(liTab.attr('data-msg'))
    var toId = msgObj.toId
    // 移除左侧tab
    liTab.parent('.user-tab').remove()
    // 移除现场
    removeLinker(toId)
    
    // 设置正在联系人的个数
    $('.links-count').text(parseInt($('.links-count').text())-1)
    // 修改标题
    $('.right-title span').text('')
    //console.log(Horn.getComp('evaluateText').getValue() + "," + Horn.getComp('evaluateGrade').getValue())
    Horn.getComp('evaluateWin').hide()
    //请求关闭
    $.post("http://"+ PLATFORM.getPath()+"/chat/close.json", {
   		clientId: msgObj.fromId, 
   		staffId: msgObj.toId,
   		evaluateText: Horn.getComp('evaluateText').getValue(), 
   		evaluateGrade: Horn.getComp('evaluateGrade').getValue() 
   	      },function(data) {
   		 if(data.isSucc == 1) {
   		     Horn.Tip.success('评价成功，感谢您的评价！')
   		 } else {
   		     
   		 }
   	      }, "json")
    	Message.toId = null;
	Message.toName = null;
    //选择一个li显示
    liTab = $('.user-tab .username')
    if(liTab.length > 0) {
	$(liTab[0]).click()
    } else {
	// 清空聊天面板
	$('.chat-msg').html('')
	Message.isFirst = true
    }
}

// 点击发起评价
var evaluationStart = function(i) {
    if(i) {
	$(i).prev().prev().click()
    }
    if($('.user-tab.user-tab-choosed .username').length == 0) {
	Horn.Tip.info('您还没有向任何人发起咨询请求！无法发起评价！')
	return 
    }
    Horn.getComp('evaluateWin').show()
}


var genLinkingHTML = function(msgObj) {
    var msg = JSON.stringify(msgObj)
    var htmlStr = "<div class='user-tab user-tab-choosed'>"+
        "<div class='username' data-msg='"+ msg +"'>"+ 
          (msgObj.toName||'客户') +
        "</div><b class='unread'></b>" +
        "<i class='fa fa-close' onclick='evaluationStart(this)'></i>" + 
      "</div>"
    // 让当前的tab被选中
    $('.user-tab-choosed').removeClass('user-tab-choosed')
    $('.links-list').append(htmlStr)
    
    var u = $('.username')
    $(u[u.length - 1]).click(function() {
      var msgObj = JSON.parse($(this).attr('data-msg'))
      // 保存聊天
      setLinker(Message.toId, $('.chat-msg').html())
      // 调整Message参数
      adjustMessage(msgObj)
      // 加载聊天
      rendererChatPanel(Message.toId)
      
      // 改变title
      $('.right-title span').text(msgObj.toName)
      
      // 去掉未读消息个数和值
      $(this).next('b').css('display', 'none')
      $(this).next('b').text('')
      autoScroll($('.chat-msg'), 7)
      
      // 如果聊天记录框打开了，更新聊天记录框
      if($('.chat-records').css('display') != 'none') {
        openChatRecordPanel()
      }
      
      $('.user-tab-choosed').removeClass('user-tab-choosed')
      $(this).parent().addClass('user-tab-choosed')
      return false
    })
  }



var setLinker = function(userId, records) {
    localStorage.setItem("CLIENT-CHAT-WITH-"+userId, records)
}

var getLinker = function(userId) {
    return localStorage.getItem("CLIENT-CHAT-WITH-"+userId) || ''
}

var removeLinker = function(userId) {
    localStorage.removeItem("CLIENT-CHAT-WITH-"+userId)
}

function setCursorPosition(elem, index) {
  var val = elem.value
  var len = val.length
  // 超过文本长度直接返回
  if (len < index) return
  elem.focus()
  if(elem.setSelectionRange) { // 标准浏览器
    elem.setSelectionRange(index, index)   
  } else { // IE9-
    var range = elem.createTextRange()
    range.moveStart("character", -len)
    range.moveEnd("character", -len)
    range.moveStart("character", index)
    range.moveEnd("character", 0)
    range.select()
  }
}

/**
 * 根据选中不同的tab调整Message对象里面的值
 * 
 * @returns
 */
function adjustMessage(msgObj) {
    Message.toId = msgObj.toId
    Message.toName = msgObj.toName
}


/**
 * 将发送的时间生成tag
 * 
 * @param str
 * @returns
 */
function genSendTag(msgObj) {
    
    var str = msgObj.msg
    if(msgIsImg(msgObj)){
	str = genImgFromBase64Str(str)
    }
    
    if(lastOpTime == undefined) {
	lastOpTime = new Date().getTime()
	genTimestamp()
    }
    var interval = new Date().getTime() - lastOpTime
    if(interval > INTERVAL) {
      genTimestamp()
    }
    var failHTMLStr
    lastOpTime = new Date().getTime()
    if(WS.webSocket==null||WS.webSocket.readyState != 1) {
	failHTMLStr = "<div class='send-fail' title='发送失败！点击重新发送'><i class='fa fa-exclamation'></i></div>"
    } else {
	failHTMLStr = ''
	// 将附加项的隐藏
	$('.addition').css('display', 'none')
    }
    // "<img src='img/user.png' alt='头像2'>"+
    var chatPanel = $('.chat-msg')
    var htmlStr = "<div class='right'>" +
    "<div class='head-img'>" +
    	"<div style=\""+"background-image:url('img/user.png')"+"\"></div>"+
    "</div>"+
    "<div class='text'>" +
    "<span class='chat-content'>"+ str+"</span>"+
    		"</div>" +failHTMLStr +
    		"</div></div>"
    chatPanel.html(chatPanel.html() + htmlStr)
    // 绑定重发事件
    resendBind()
    
    if(WS.webSocket == undefined || WS.webSocket == null || WS.webSocket.readyState != 1) {
	// 设定重发标签的位置
	adjustFailTip()
    }
    

    // 自动滚动
    autoScroll(chatPanel, 7)
    
    if(msgIsImg(msgObj)){
	// 更新图片查看器
	viewerUpdate()
    }
	
    
    // Echo测试
    // genRecvTag(str)
}


var autoScroll = function(chatPanel,n) {
    var htmlStr = ""
    for(var i=0; i<n; i++) {
	htmlStr += "<br data-autoScroll/>"
	
    }
    chatPanel.find("br[data-autoScroll]").remove()
    chatPanel.append(htmlStr)
    chatPanel.scrollTop(99999);
}



/**
 * 将收到的信息生成tag
 * 
 * @param str
 * @returns
 */
function genRecvTag(msgObj) {
    var str = msgObj.msg
    if(msgIsImg(msgObj)){
	str = genImgFromBase64Str(str)
    }
    if(lastOpTime == undefined) {
	lastOpTime = new Date().getTime()
	genTimestamp()
    }
    var interval = new Date().getTime() - lastOpTime
    if(interval > INTERVAL) {
      genTimestamp()
    }
    lastOpTime = new Date().getTime()
    
    // "<img src='img/user.png' alt='头像1'/>"+
    var chatPanel = $('.chat-msg')
    var htmlStr = "<div class='left'>" +
    "<div class='head-img'>" +
    	"<div style=\""+"background-image:url('img/user.png')"+"\"></div>"+
    "</div>"+
    "<div class='text'>"+
    "<span class='chat-content'>"+ str+ "</span></div></div></div>"
    
    chatPanel.html(chatPanel.html() + htmlStr)
    autoScroll(chatPanel, 7)
    if(msgIsImg(msgObj)){
	// 更新图片查看器
	viewerUpdate()
    }
}

/**
 * 生成时间戳
 * 
 * @returns
 */
function genTimestamp() {
    var chatPanel = $('.chat-msg')
    var htmlStr = "<div class='mid'>" +
          "<span class='timestamp'>"+ curTime() +"</span></div>"
    chatPanel.html(chatPanel.html() + htmlStr)
}


/**
 * 将时间戳转为日期
 * 
 * @param timestamp
 * @returns
 */
function timeByTimestamp(timestamp) {
    var d = new Date(parseInt(timestamp.val)).format("yyyy-MM-dd hh:mm:ss");
    return d.toLocaleString()
}


/**
 * 生成时间，只包含时、分
 * 
 * @returns
 */
function curTime() {
    var time = new Date()
    var minute = time.getMinutes()+''
    if(minute.length == 1) {
	minute = '0' + minute
    }
    var hour = time.getHours()+''
    if(hour.length == 1) {
	hour = '0' + hour
    }
    return hour+':'+ minute
}

/**
 * 关闭聊天记录框
 */
var closeChatRecordPanel = function () {
    $('.chat-records').css('display', 'none')
    $('.chat-records').removeClass('g-grid-6')
    $('.tpanel-right').removeClass('g-grid-4')
    $('.tpanel-right').addClass('g-grid-10')
    adjustFailTip()
}

/**
 * 打开聊天记录框
 */
var openChatRecordPanel = function() {
    loadChatRecords(Message.fromId, Message.toId)
    $('.chat-records').css('display', 'block')
    $('.chat-records').addClass('g-grid-6')
    $('.tpanel-right').addClass('g-grid-4')
    $('.tpanel-right').removeClass('g-grid-10')
    adjustFailTip()
}

var loadChatRecords = function(fromId, toId) {
    if(!fromId || !toId) {
	return []
    }
    $.ajax({
     	type: "post",
        url: "http://"+ PLATFORM.getPath()+"/chat/getChatRecord.json",
        async: false,
        dataType: "json",
        data: {
            fromId: fromId,
            toId: toId
        },
        success: function(data) {
            Horn.getComp('chatRecords').loadData(data)
        }
      });
}

/**
 * 根据toId记录渲染界面
 */
/**
 * 根据toId记录渲染界面
 */
var rendererChatPanel = function(toId) {
    // 去除附加项
    $('.addition').css('display', 'none')
    // console.log(getLinker(toId))
    $('.chat-msg').html(getLinker(toId))
}

// 页面刷新后从新渲染页面
var renderAfterReload = function() {
    var str
    var msgObj = Object.assign({} ,Message)
    for(var x in localStorage) {
	if(x.startsWith("CLIENT-CHAT-WITH-")) {
	    msgObj.toId = x.split('-')[3]
	    genLinkingHTML(msgObj)
	    $('.chat-msg').html(localStorage[x])
	}
    }
}



/**
 * 根据toId获取聊天记录JSON串
 * 
 * @returns
 */
function getChatRecords(toId) {
    return localStorage.getItem("CLIENT-CHAT-WITH-"+userId) || "[]"
}
/**
 * 根据toId清除聊天记录
 * 
 * @returns
 */
function clearChatRecords(toId) {
    alert('清除聊天记录')
}

function testbeforeLoad() {
    // alert('testbeforeLoad')
}

function testloadSuccess(data) {
    console.log('testloadSuccess')
}

function testloadError() {
    alert('testloadError')
}



/**
 * 添加一条聊天记录 未登录状态使用该方法进行缓存，聊天记录的key值为toId
 * 
 * @returns
 */
/*function addChatRecord(msgObj) {
    if(isLogined) {
	// 添加聊天记录到服务器
    }
    // 添加到本地
    if(storageAvailable('localStorage')) {
	var recodes = localStorage.getItem(msgObj.toId) || '[]'
	recodes = JSON.parse(recodes)
	recodes.push(msgObj)
	try {
	    localStorage.setItem(msgObj.toId, JSON.stringify(recodes))
	} catch(e) {
	    if (e.name == 'QuotaExceededError') {
		// 存放满了，清除缓存
		localStorage.clear()
	    }
	}
    }
}*/


function storageAvailable(type) {
    try {
        var storage = window[type],
            x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return e instanceof DOMException && (
            // everything except Firefox
            e.code === 22 ||
            // Firefox
            e.code === 1014 ||
            // test name field too, because code might not be present
            // everything except Firefox
            e.name === 'QuotaExceededError' ||
            // Firefox
            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
            // acknowledge QuotaExceededError only if there's something already
	    // stored
            storage.length !== 0;
    }
}

function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
   
    if (len) {
     // Compact form
     for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
     // rfc4122, version 4 form
     var r;
   
     // rfc4122 requires these characters
     uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
     uuid[14] = '4';
   
     // Fill in random data. At i==19 set the high bits of clock sequence as
     // per rfc4122, sec. 4.1.5
     for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
       r = 0 | Math.random()*16;
       uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
     }
    }
   
    return uuid.join('');
  }


/**
 * 调整fail tip与对话记录的距离
 * 
 * @returns
 */
function adjustFailTip() {
    var rs = $('.right .text .chat-content')
    
    for(var i=0,len=rs.length; i<len; i++) {
	var r = rs[i]
	var width = $(r).css('width')
	var paddingLeft = $(r).css('padding-left')
	var paddingRight = $(r).css('padding-right')
	var totalWidth = parseInt(width.substring(0, width.length-2))
	+ parseInt(paddingLeft.substring(0, paddingLeft.length-2))
	+ parseInt(paddingRight.substring(0, paddingRight.length-2))
	// console.log(totalWidth)
	var sf = $('.right .send-fail')
	var s = sf[i]
	var textWidthStr = $('.right .text').css('width')
	var textWidth = parseInt(textWidthStr.substring(0, textWidthStr.length-2))
	$(s).css('left', (textWidth - totalWidth - 20) + 'px')
    }
    
    
}






